package tc.jv.task11;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import tc.jv.task4.Vector;
import tc.jv.task8.Vectors;
import tc.jv.task9.IncompatibleVectorSizeException;

public class ParallelServer
{
	
	class Task extends Thread
	{
		
		private final Socket socket;
		private final String name;
		
		public Task(Socket socket)
		{
			this.socket = socket;
			this.name = "Task" + getId() + "> ";
		}
		
		public void run()
		{
			InputStream  in;
			OutputStream out;
			
			Vector v1, v2, result;
			
			try
			{
				in  = socket.getInputStream();
				out = socket.getOutputStream();
				
				System.out.println(name + "Waiting...");
				
				v1 = Vectors.inputVector(in);
				System.out.println(name + "Received: ");
				v1.print(1);
				v2 = Vectors.inputVector(in);
				System.out.println(name + "Received: ");
				v2.print(1);
				
				result = null;
				try
				{
					result = Vectors.add(v1, v2);
				}
				catch (IncompatibleVectorSizeException e) {}
				
				System.out.println(name + "Sending back: ");
				System.out.println(result);
				Vectors.outputVector(result, out);
				System.out.println(name + "Sent.");
				
				socket.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		
	}
	
	public final int port;
	private ServerSocket serverSocket;
	
	private static final String name = "Server> ";
	
	public ParallelServer(final int port)
	{
		this.port = port;		
		
		try
		{
			serverSocket = new ServerSocket(port);
			
			while (true)
			{
				System.out.println(name + "Waiting for a client...");
				Socket socket = serverSocket.accept();
				System.out.println(name + "Got a client");
				
				new Task(socket).start();
			}			
		}
		catch (IOException e)
		{
			System.err.println(name + "Could not listen on port: " + port);
			e.printStackTrace();
		}
	}
	
	@Override
	protected void finalize() throws Throwable
	{
		super.finalize();
		serverSocket.close();
		System.out.println(name + "Closed.");
	}

	public static void main(String[] args)
	{
		new ParallelServer(12011);
	}
	
}
